﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for VoucherManager
/// </summary>
public class VoucherManager
{
    private debioscoopEntities db;

    public VoucherManager(debioscoopEntities db)
	{
        this.db = db;
	}

    public voucher getVoucher(int voucherID)
    {
        voucher voucher = db.vouchers.Where(v => v.voucher_code == voucherID && v.voucher_actief == true && v.voucher_bedrag > 0).FirstOrDefault(); 
        return voucher;
    }

    public double getDiscount(int voucherID, double totalCost)
    {
        double discount = 0;
        voucher currentVoucher = this.getVoucher(voucherID);

        if (currentVoucher.voucher_bedrag > totalCost)
        {
            discount = totalCost;
            currentVoucher.voucher_bedrag = currentVoucher.voucher_bedrag - totalCost; 
        }
        else
        {
            discount = (double)currentVoucher.voucher_bedrag;
            currentVoucher.voucher_bedrag = 0;
            currentVoucher.voucher_actief = false;
        }
      
        this.executeQuery();
        return discount;
    }

    public void deactivateVoucher()
    {

    }

    public void executeQuery()
    {
        try
        {
            db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.InnerException);
        }
    }
}